<template>
  <div>
    <UploadExcel :on-success="handleSuccess" />
  </div>
</template>

<script>
// import UploadExcel from '@/components/UploadExcel'
import { reqAddEmployeeBatch } from '@/api/employees'
export default {
  name: 'Import',
  // components: { UploadExcel },
  methods: {
    handleSuccess({ header, results }) {
      // console.log(obj)
      // console.log(header, results, '00000')
      // header中, results中的数据是中文的, 但是提交给后台的要是英文的
      // 中英文对照
      if (this.$route.query.type === 'user') {
        this.handleEmployeeBatch(header, results)
      }
    },
    async handleEmployeeBatch(header, results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      // const arr = []
      // results.forEach(item => {
      //   const obj = {}
      //   for (const key in item) {
      //     const engKey = userRelations[key]
      //     obj[engKey] = item[key]
      //   }
      //   arr.push(obj)
      // })
      // console.log(arr)

      // 数据格式转换 1. 拷贝对象 2. 中文键 换成英文键
      // 所有访问对象属性的地方[]
      const arr = []
      results.forEach(item => {
        const obj = {}
        for (const key in item) {
          const replaceName = userRelations[key]
          // console.log(res)
          if (replaceName === 'timeOfEntry' || replaceName === 'correctionTime') {
            // 表示你正在给入职日期 转正日期 赋值, 需要转换
            obj[replaceName] = this.formatExcelDate(item[key], '-')
          } else {
            obj[replaceName] = item[key]
          }
        }
        // console.log(obj)
        arr.push(obj)
      })
      // console.log(arr)
      await reqAddEmployeeBatch(arr)
      this.$message.success('批量导入员工成功')
      // 回到员工页
      // this.$router.push('/employees')
      this.$router.back()
    },
    // 将excel中的时间转成js中的时间 formatExcelData(67890, '-')
    formatExcelDate(numb, format) {
      const time = new Date(numb * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
